//
//  eyrUserTableViewController.m
//  eyr
//
//  Created by Tor Gjøsæter on 4/24/12.
//  Copyright (c) 2012 University of Bergen. All rights reserved.
//

#import "UserTableVC.h"
#import "User.h"
#import "User+DefaultData.h"
#import "UserDao.h"
#import "GraphVC.h"
#import "HelpScrollVC.h"


@interface UserTableVC ()

@end

@implementation UserTableVC


@synthesize userTableView;
@synthesize deleteUserButton;
@synthesize popoverController;



- (void) setupFetchedResultsController{
    UserDao *ud = [UserDao sharedSingleton];
    
    NSFetchRequest *request = [NSFetchRequest  fetchRequestWithEntityName:@"User"];
    request.sortDescriptors = [NSArray  arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]];    
    
    self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
                                                                        managedObjectContext:ud.userDataBase.managedObjectContext
                                                                          sectionNameKeyPath:nil 
                                                                                   cacheName:nil];

}

- (void) viewDidAppear:(BOOL)animated{
    [self performFetch];
}



- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    
    //Segue til grafen
    if([segue.identifier isEqualToString:@"PushToGraphVC"]){    
        
        NSIndexPath *indexPath = [self.userTableView indexPathForCell:sender];
        
        User *user = [self.fetchedResultsController objectAtIndexPath:indexPath];
        
        if([segue.destinationViewController respondsToSelector:@selector(setUser:)]){
        
            [segue.destinationViewController setUser:user];
        }       
    }
    
    
    //Segue til adduser
    if([segue.identifier isEqualToString:@"ShowAddUserSegue"]){   
           if ([segue isKindOfClass:[UIStoryboardPopoverSegue class]])
        {
            UIStoryboardPopoverSegue *popoverSegue = (UIStoryboardPopoverSegue *)segue;
            [self.popoverController dismissPopoverAnimated:YES];
            self.popoverController = popoverSegue.popoverController; // might want to be popover's delegate and self.popoverController = nil on dismiss?
        }
        
    }
    
    if([segue.identifier isEqualToString:@"segueToGeneralHelpPopover"]){   
        NSLog(@"Segue to segueToGeneralHelpPopover");
        
      //  UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil]; 
      //  UIViewController *helpGeneralVC = (UIViewController *)[storyboard instantiateViewControllerWithIdentifier:@"HelpGeneral"];

        if ([segue.destinationViewController respondsToSelector:@selector(setIdentifier:)]) {
            [segue.destinationViewController performSelector:@selector(setIdentifier:) 
                                                  withObject:@"HelpGeneral"];
        } 
       
       
        if ([segue isKindOfClass:[UIStoryboardPopoverSegue class]]) //For å få vekk muchos poppus
        {
            UIStoryboardPopoverSegue *popoverSegue = (UIStoryboardPopoverSegue *)segue;
            [self.popoverController dismissPopoverAnimated:YES];
            self.popoverController = popoverSegue.popoverController; // might want to be popover's delegate and self.popoverController = nil on dismiss?
        }
        
    }

    
}

- (void) viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    UserDao *ud = [UserDao sharedSingleton];    
    [ud addTestBruker];
    [self setupFetchedResultsController];   
    
}

//Denne plukker action frå deleteknotten
- (void)tableView:(UITableView *)tableView commitEditingStyle:
  (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
     
    

    [tableView beginUpdates];    
    User *user = [self.fetchedResultsController objectAtIndexPath:indexPath];
    NSLog(@"Deleting user %@", user.name);
    UserDao *ud = [UserDao sharedSingleton];
    [ud deleteUserObject:user.name];
    [self performFetch]; //Denne må me kjøre her slik at den får oppdatert kor mange ting det finnest i skiten.
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:YES];              
    [tableView endUpdates];
    
    
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"User Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    // Configure the cell...
    User *user = [self.fetchedResultsController objectAtIndexPath:indexPath];
    cell.textLabel.text = @"Navn";
    cell.detailTextLabel.text = user.name;
    return cell;
}



- (IBAction)refreshUsers:(id)sender {
    
        [self performFetch];
}

- (IBAction)deleteUser:(id)sender {
    
    
    if(self.editing)
    {
        [super setEditing:NO animated:NO];
        [userTableView setEditing:NO animated:YES];
        [userTableView reloadData];

        [deleteUserButton setTitle:@"Edit user"];
        UserDao *ud = [UserDao sharedSingleton];
        
        [ud commitUserDelete];
        [self performFetch];//Denne på magisk vis committer endring?????
    }
    else
    {
        [super setEditing:YES animated:YES];
        [userTableView setEditing:YES animated:YES];
        [userTableView reloadData];
        [deleteUserButton setTitle:@"Done"];
        
    }
    
}
- (void)viewDidUnload {
[self setUserTableView:nil];

    [self setDeleteUserButton:nil];

    [super viewDidUnload];
}
                          
- (IBAction)refreshUsersButton:(id)sender {
    NSLog(@"Refreshing uzers");
        [self performFetch];
}


@end
